import { useContext, useState } from 'react';

import { ModalContext } from '@/shared/context/ModalContext';
import { Button, ButtonVariants, Loader, Modal, Tooltip } from '@/shared/ui';
import cn from 'classnames';
import { useCopyToClipboard, useIsClient } from 'usehooks-ts';

import { shareUrls } from '../../config';
import { ReactComponent as CopyIcon } from '../../icons/copy-icon.svg';
import cs from './ShareModal.module.scss';

export const ShareModal = () => {
  const [isShow, setIsShow] = useState(false);
  const { closeModal } = useContext(ModalContext);
  const isClient = useIsClient();
  const [, copy] = useCopyToClipboard();
  async function copyTextToClipboard(text?: string) {
    if (!text) {
      return;
    }
    await copy(text);
    setIsShow(() => true);
    setTimeout(() => {
      setIsShow(() => false);
    }, 1500);
  }
  return (
    <Modal className={cs.modal} containerClassName={cs.container} isOpen onCloseClick={closeModal}>
      <h2 className={cs.title}>Поделиться</h2>
      <div className={cs.clipboard} onClick={() => copyTextToClipboard(window.location.href)}>
        <div className={cn(cs.url, isClient && window.location.href.length > 50 && cs.hide)}>
          {isClient ? window.location.href : <Loader />}
        </div>
        <Tooltip isOpen={isShow} text="Скопировано">
          <button className={cs.copy} type="button">
            <CopyIcon />
          </button>
        </Tooltip>
      </div>
      <div className={cs.links}>
        {isClient ? (
          shareUrls.map(({ id, link, component }) => (
            <Button
              className={cs.link}
              href={link + window.location.href}
              key={id}
              link
              variant={ButtonVariants.Secondary}
            >
              {component}
            </Button>
          ))
        ) : (
          <Loader height={64} width={280} />
        )}
      </div>
    </Modal>
  );
};
